<template>
  <div id="folder-container">
    <h1>文件夹</h1>
    <!--文件夹页面盒子-->
    <div class="recently-folder">
      <!--资源库题目搜索区域-->
      <div class="recently-folder-header">
        <div class="recently-folder-header-title">最近更新</div>
        <div class="recently-folder-header-right">
          <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
          <el-input placeholder="输入关键词搜索" v-model="keyword" @change="search"></el-input>
          <div class="block">
            <el-date-picker
                v-model="dateRange"
                type="daterange"
                align="right"
                @change="search"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
            </el-date-picker>
          </div>
        </div>
      </div>
      <!--资源库题目搜索区域结束-->
      <!--面包屑-->
      <el-breadcrumb separator=">">
        <el-breadcrumb-item><span @click="getFolderList">文件夹</span></el-breadcrumb-item>
        <el-breadcrumb-item v-for="(bread,index) in breadcrumbStack" :key="bread.fileId"><span
            @click="breadcrumbStackClick(bread,index)">{{ bread.name }}</span></el-breadcrumb-item>
      </el-breadcrumb>
      <!--面包屑结束-->
      <!--文件夹主题区域-->
      <div class="folder-content" @contextmenu.prevent="folderContentClickDown($event)" @click="isEditorFolder = false">
        <div class="folder-tabulation" v-show="!$isEmpty(fileList)">
          <div class="folder-item" v-for="(file,index) in fileList" :key="file.fileId" @click="openFile(file)">
            <img :src="fileTypeImg[file.type]" alt="">
            <div class="folder-name">{{ file.name }}</div>
            <div class="folder-create-time">{{ file.createdTime }}</div>
          </div>
        </div>
        <div v-show="$isEmpty(fileList)" class="no-folder">
          <span>暂无文件</span>
        </div>
      </div>
      <!--文件夹主题区域结束-->
    </div>
    <!--文件夹页面盒子结束-->
    <!--右键编辑弹窗-->
    <div class="folder-editor" id="folder-editor" v-show="isEditorFolder">
      <div class="folder-editor-option new-folder" @click="openNewFileDialog(FileType.folder)">新建文件夹</div>
      <div class="folder-editor-option new-note" @click="openNewFileDialog(FileType.note)">新建笔记</div>
      <el-popover
          placement="right"
          width="200"
          class="folder-editor-option sort-order-popover"
          trigger="click">
        <div class="folder-secondary-option sort-order">名称</div>
        <div class="folder-secondary-option sort-order">创建日期</div>
        <div class="folder-secondary-option sort-order">类型</div>
        <div slot="reference" class="folder-secondary-menu"><span>排序方式</span><span>></span></div>
      </el-popover>
    </div>
    <!--右键编辑弹窗结束-->
    <!--新建文件弹窗-->
    <el-dialog
        :title="newFile.newFileTitle"
        :visible.sync="newFolderDialog"
        class="dialog-flex-column"
        width="25%"
        top="20vh"
        center>
      <div class="dialog-img-box">
        <img :src="fileTypeImg[newFile.fileType || 'folder']" alt="">
      </div>
      <el-input ref="new-file-name-input" placeholder="请输入文件夹名称" v-model="newFile.fileName" ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="newFolderDialog = false">取 消</el-button>
        <el-button type="primary" @click="addFile()">确 定</el-button>
      </span>
    </el-dialog>
    <!--新建文件弹窗结束-->
  </div>
</template>
<script>
import {FileType,File} from "@/entity/file";
export default {
  name: "folder",
  data() {
    return {
      // 文件夹
      File,
      // 文件夹类型
      FileType,
      // 新建文件
      newFile:{
        name: '',
        type: '',
      },
      newFolderDialog: false,
      // 路径栈
      breadcrumbStack: [],
      // 是否编辑文件夹
      isEditorFolder: false,
      // 用户信息
      user: sessionStorage.getItem('user') ? JSON.parse(sessionStorage.getItem('user')) : null,
      // 搜索关键字
      keyword: '',
      // 文件列表
      fileList: [],
      // 父文件夹id
      parentFolderId: null,
      // 文件类型图片
      fileTypeImg: {
        note: require('@/assets/img/note.svg'),
        folder: require('@/assets/img/folder.svg'),
      },
      // 文件夹项索引
      folderItemIndex: -1,
      // 选择器选项
      pickerOptions: {
        shortcuts: [{
          // 文本
          text: '最近一周',
          // 点击事件
          onClick(picker) {
            // 获取当前时间
            const end = new Date();
            // 设置开始时间
            const start = new Date();
            // 设置开始时间为当前时间减去一周
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            // 触发选择器
            picker.$emit('pick', [start, end]);
          }
        }, {
          // 文本
          text: '最近一个月',
          // 点击事件
          onClick(picker) {
            // 获取当前时间
            const end = new Date();
            // 设置开始时间
            const start = new Date();
            // 设置开始时间为当前时间减去一个月
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            // 触发选择器
            picker.$emit('pick', [start, end]);
          }
        }, {
          // 文本
          text: '最近三个月',
          // 点击事件
          onClick(picker) {
            // 获取当前时间
            const end = new Date();
            // 设置开始时间
            const start = new Date();
            // 设置开始时间为当前时间减去三个月
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            // 触发选择器
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 日期范围
      dateRange: '',
    };
  },
  methods: {

    /**
     * 新建文件
     */
    async addFile() {
      if(this.$isEmpty(this.newFile?.fileName)) return this.$messageHelper.messageWarning(`请输入${this.newFile?.fileTypeName || '文件'}名称`);
      let res = await this.$request.post("/files/newFile",this.newFile);
      if (res.data.code !== 200) return this.$messageHelper.messageWarning(res.data.msg);
      this.newFolderDialog = false;
      this.getFilesByParentFolderId(this.parentFolderId);
      console.log(res, 1111)
    },
    /**
     * 打开新建文件弹窗
     */
    openNewFileDialog(type) {
      this.isEditorFolder = false;
      this.newFolderDialog = true;
      this.newFile = File.newFileByType(type, this.parentFolderId);
      this.$nextTick(() => {
        this.$refs["new-file-name-input"].$el.querySelector('input').select();
      });
      console.log(this.newFile, 1111)
    },
    /**
     * 文件夹内容点击事件 弹窗（新建文件夹 新建笔记 排序方式）
     * @param event
     */
    folderContentClickDown(event) {
      console.log('鼠标位置:', event.clientX, event.clientY);
      let folderEditor = document.getElementById('folder-editor')
      console.log(folderEditor, 1111)
      this.$nextTick(() => {
        this.isEditorFolder = true;
        folderEditor.style.left = event.clientX + 'px';
        folderEditor.style.top = event.clientY + 'px';
      })
    },
    // 打开文件
    async openFile(file) {
      console.log(file.type, 111)
      if (file.type === 'note') return this.toNoteDetail(file.noteId);
      if (file.type === 'folder') return this.openFolder(file);
    },
    // 打开文件夹
    async openFolder(folder) {
      this.getFilesByParentFolderId(folder.folderId);
      this.breadcrumbStackPush(folder);
    },
    getFilesByParentFolderId(parentFolderId) {
      if (parentFolderId === 0) return this.getFolderList();
      this.$request.get(`folder/openFolder?userId=${this.user.userId}&parentFolderId=${parentFolderId}`).then(res => {
        if (res.data.code !== 200) return this.$messageHelper.messageWarning(res.data.msg);
        this.fileList = res.data.data.fileList;
        this.parentFolderId = parentFolderId;
      })
    },
    // 面包屑栈推入
    breadcrumbStackPush(folder) {
      console.log(folder, 222)
      this.breadcrumbStack.push(folder);
    },
    // 面包屑栈弹出
    breadcrumbStackPop(folder, index) {
      this.breadcrumbStack.splice(index + 1);
      this.parentFolderId = folder.folderId;
    },
    // 面包屑栈点击
    async breadcrumbStackClick(folder, index) {
      let res = await this.$request.get(`folder/openFolder?userId=${this.user.userId}&parentFolderId=${folder.folderId}`);
      if (res.data.code !== 200) return this.$messageHelper.messageWarning(res.data.msg);
      this.fileList = res.data.data.fileList;
      this.breadcrumbStackPop(folder, index);
    },
    // 收藏文件夹
    collectionFile(folder) {
      this.$request.get('/folder/collection', {
        folderId: folder.folderId
      }).then(res => {
        if (res.data.code === 200) {
          this.$messageHelper.messageSuccess('收藏成功');
        } else {
          this.$messageHelper.messageWarning(res.data.msg);
        }
      })
    },
    // 删除文件夹
    deleteFile(folder) {
      this.$request.post('/user/delete', {
        userId: this.user.userId,
        folderId: folder.folderId,
      }).then(res => {
        if (res.data.code === 200) {
          this.$messageHelper.messageSuccess('删除成功');
          this.getFolderList();
        } else {
          this.$messageHelper.messageWarning(res.data.msg);
        }
      })
    },
    /**
     * 搜索
     * @return {Promise<void>}
     */
    search() {
      let date = this.dateRange ? this.dateRange[0] : null;
      let startTime = date ? date.toISOString().substring(0, 19).replace('T', ' ') : null;
      date = this.dateRange ? this.dateRange[1] : null;
      let endTime = date ? date.toISOString().substring(0, 19).replace('T', ' ') : null;
      console.log(startTime, endTime)
      this.$request.post('/folder/search', {
        userId: this.user.userId,
        keyword: this.keyword,
        startTime,
        endTime,
      }).then(res => {
        if (res.data.code !== 200) this.$messageHelper.messageWarning(res.data.msg);
        res.data.data ? this.fileList = res.data.data.fileList : [];
      })
    },

    // 获取文件夹列表
    getFolderList() {
      this.$request.get('/folder/listByUserId?userId=' + this.user.userId).then(res => {
        if (res.data.code !== 200) this.$messageHelper.messageWarning(res.data.msg);
        this.parentFolderId = 0;
        console.log(res.data.data.fileList.list)
        res.data.data ? this.fileList = res.data.data.fileList.list : [];
        this.breadcrumbStack = [];
      })
    },

    // 跳转到笔记详情
    toNoteDetail(noteId) {
      this.$currentNote.folderId = noteId;
      this.$router.push('/index/NoteEditor');
    },
  },
  watch: {
    /**
     * 文件列表
     * desc
     * 1. 监听文件列表，当文件列表发生变化时，对文件列表中的时间进行格式化
     */
    fileList: {
      handler(val) {
        Array.isArray(val) && val.forEach(item => {
          let createdTime = new Date(item.createdTime);
          let updatedTime = new Date(item.updatedTime);
          item.createdTime = createdTime.getFullYear() + '/' + (createdTime.getMonth() + 1).toString().padStart(2, '0') + '/' + createdTime.getDate().toString().padStart(2, '0') + ' ' + createdTime.getHours().toString().padStart(2, '0') + ':' + createdTime.getMinutes().toString().padStart(2, '0') + ':' + createdTime.getSeconds().toString().padStart(2, '0');
          item.updatedTime = updatedTime.getFullYear() + '/' + (updatedTime.getMonth() + 1).toString().padStart(2, '0') + '/' + updatedTime.getDate().toString().padStart(2, '0') + ' ' + updatedTime.getHours().toString().padStart(2, '0') + ':' + updatedTime.getMinutes().toString().padStart(2, '0') + ':' + updatedTime.getSeconds().toString().padStart(2, '0');
        })
      },
      deep: true
    }
  },
  mounted() {
    // 禁用右键菜单
    document.addEventListener('contextmenu', function (e) {
      e.preventDefault();
    })
    this.getFolderList();
  },
  beforeDestroy() {
    document.removeEventListener('contextmenu', function (e) {
      e.preventDefault();
    })
  }
};
</script>
<style lang="less" scoped>
#folder-container {
  width: 100%;
  height: 100%;
  background: #fff;
  display: flex;
  flex-direction: column;
  padding: 20px 22px;

  h1 {
    text-align: left;
    font-size: 36px;
  }

  //最近更新
  .recently-folder {
    margin-top: 20px;
    width: 100%;
    height: 100%;

    //最近更新标题
    .recently-folder-header {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 20px;

      //最近更新标题右侧
      .recently-folder-header-right {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        gap: 10px;

        .el-input {
          width: 180px;
        }

        .el-select {
          width: 155px;
          //min-width: 155px;
        }
      }
    }

    //面包屑
    .el-breadcrumb {
      font-size: 18px;
      height: 30px;
      margin-bottom: 20px;

      .el-breadcrumb__item {
        &:hover {
          cursor: pointer;
          color: #409EFF;
        }
      }

    }

    //文件夹内容
    .folder-content {
      height: calc(100% - 100px);

      //文件夹列表
      .folder-tabulation {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        gap: 20px;

        .folder-item {
          width: 150px;
          height: 150px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          border-radius: 10px;
          cursor: pointer;

          &:hover {
            background: #f5f5f5;
          }

          img {
            width: 70px;
            height: 70px;
          }

          .folder-name {
            margin-top: 10px;
            font-size: 18px;
            font-weight: bold;
          }

          .folder-create-time {
            margin-top: 10px;
            font-size: 16px;
            color: #909399;
          }
        }

      }

      .no-folder {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 26px;
        color: #909399;
      }
    }
  }

  //文件夹编辑
  .folder-editor {
    position: fixed;
    display: flex;
    width: 160px;
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
    background: #fff;
    border-radius: 10px;
    padding: 6px 10px;
    border: 1px solid #ebeef5;

    .folder-editor-option {
      width: 100%;
      text-align: left;
      font-family: "微软雅黑";
      font-size: 18px;
      padding: 6px 10px;
      cursor: pointer;

      &:hover {
        cursor: pointer;
        color: #409EFF;
      }

      .folder-secondary-menu {
        display: flex;
        justify-content: space-between;
      }

      .folder-secondary-option {
        padding: 6px 10px;
        cursor: pointer;

        &:hover {
          cursor: pointer;
          color: #409EFF;
          font-size: 18px;
        }
      }
    }
  }
}

.el-popover {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 20px;

  .sort-order {
    padding: 6px 10px;
    cursor: pointer;

    &:hover {
      cursor: pointer;
      color: #409EFF;
    }
  }
}


</style>
